package com.zixuan.sina.config.schedule;

import com.alibaba.fastjson.JSON;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@EnableScheduling//开启定时任务
@Component
@Slf4j
public class AutoGetStar {

    @Resource
    private  RedisTemplate<String,Object> redisTemplate;
    @Resource
    private UserService userService;
    /**
     * 持久化点赞数据
     */

//    @Scheduled(cron ="*/10 * * * * ?")//10秒更新一次数据到数据库
    public void cacheStarData(){
        Map hashValue = redisTemplate.opsForHash().entries("starValue");
        for (Object userId : hashValue.keySet()) {
            User user = new User();
            user.setId((String) userId);
            List<String> postIds = (ArrayList<String>)hashValue.get(userId);
            String jsonString = JSON.toJSONString(postIds);
            user.setThumbs(jsonString);
            userService.editUserInfo(user);
        }
        redisTemplate.opsForHash().entries("starValue").clear();
        log.info("定时任务完成");
    }


}
